const mongoose = require('mongoose')
const Schema = mongoose.Schema

// 定义 你的schema
const ticketSchema = new Schema({
  name: String,
  ticket: String,
  expires_in: Number,
  meta: {
    createdAt: {
      type: Date,
      default: Date.now()
    },
    updatedAt: {
      type: Date,
      default: Date.now()
    }
  }
})
// 数据储存的中间件  是否新增数据 isNew
ticketSchema.pre('save', function(next){
  if(this.isNew) {
    this.meta.createdAt = this.meta.updatedAt = Date.now()
    console.log('新增了一条数据。。。。。。。。。')
  } else {
    this.meta.updatedAt = Date.now()
  }
  next()
})

// 定义一个静态方法 
ticketSchema.statics = {
  async getTicket(){
    const ticket = await this.findOne({
      name: 'ticket'
    }).exec()

    if (ticket && ticket.ticket){
      ticket.ticket = ticket.ticket
    } else {
      console.log("该数据为空")
      return false
    }
    return ticket
  },

  async saveTicket(data) {
    // data 是 获取到的 ticket
    // 找到name 为 ticket 的数据
    let ticket = await this.findOne({
      name: 'ticket'
    }).exec()
 
    if (ticket) {
        ticket.ticket = data.ticket
        ticket.expires_in = data.expires_in     
    } else {    
      // new 一个数据模型的实例
      ticket = new Ticket({
        name: 'ticket',
        ticket: data.ticket,     
        expires_in: data.expires_in
      })
    }

    try {
      await ticket.save()
    } catch (e){
       console.log('存储失败')
       console.log(e)
    }
    
    return data
  }
}
// 获取数据模型
const Ticket = mongoose.model('Ticket', ticketSchema, 'Ticket')